package com.sky.mqtt;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * @Content: MQTT生产端
 * @Author: LS
 * @Date: 2023/10/13 14:43
 */
@Configuration
public class MQTTOutboundConfiguration {
    @Autowired
    private MQTTProperties mqttProperties;

    @Bean
    public MessageChannel mqttOutboundChannel(){
        return new DirectChannel();
    }

    /**
     * 生产端
     */

    @Bean
    public MqttPahoClientFactory mqttPahoClientFactory(){
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        String[] split = mqttProperties.getBroker().split(",");
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(split);
        options.setUserName(mqttProperties.getUsername());
        options.setPassword(mqttProperties.getPassword().toCharArray());
        //接收离线消息
        options.setCleanSession(false);//告诉代理客户端是否要建立持久会话;false为建立持久会话
        options.setConnectionTimeout(60);
        options.setKeepAliveInterval(60);
        factory.setConnectionOptions(options);
        return factory;
    }

    @Bean
    @ServiceActivator(inputChannel = "mqttOutboundChannel")
    public MessageHandler mqttOutbound(){
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
                mqttProperties.getClientId()+"_outbound",
                mqttPahoClientFactory()
        );
        messageHandler.setAsync(true);
        return messageHandler;
    }


}
